package org.jeecg.modules.golf.question.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.golf.question.client.QuestionPage;
import org.jeecg.modules.golf.question.client.qto.QuestionQueryPageDTO;
import org.jeecg.modules.golf.question.entity.MyQuestionPlan;
import org.jeecg.modules.golf.question.entity.PlanEffective;
import org.jeecg.modules.golf.question.entity.Question;
import org.jeecg.modules.golf.question.entity.QuestionTypeMapping;
import org.jeecg.modules.golf.question.query.QuestionQueryService;
import org.jeecg.modules.golf.question.service.IMyQuestionPlanService;
import org.jeecg.modules.golf.question.service.IQuestionService;
import org.jeecg.modules.golf.question.service.IQuestionTypeMappingService;
import org.jeecg.modules.golf.tag.entity.TagMapping;
import org.jeecg.modules.golf.tag.service.ITagMappingService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 问题
 * @Author: jeecg-boot
 * @Date:   2020-11-21
 * @Version: V1.0
 */
@Api(tags="问题")
@RestController
@RequestMapping("/question")
@Slf4j
public class QuestionController {
	@Autowired
	private IQuestionService questionService;
	@Autowired
	private IQuestionTypeMappingService questionTypeMappingService;
	@Autowired
	private ITagMappingService tagMappingService;
	@Autowired
	private IMyQuestionPlanService myQuestionPlanService;

	@Autowired
	private QuestionQueryService questionQueryService;

	/**
	 * 分页列表查询
	 * @return
	 */
	@AutoLog(value = "问题-分页列表查询")
	@ApiOperation(value="问题-分页列表查询", notes="问题-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(QuestionQueryPageDTO questionQueryPageDTO) {
		IPage<QuestionPage> page = questionQueryService.page(questionQueryPageDTO);
		return Result.OK(page);
	}


	@AutoLog(value = "问题-分页列表查询")
	@ApiOperation(value="问题-分页列表查询", notes="问题-分页列表查询")
	@PostMapping(value = "/done")
	public Result<?> done(@RequestBody Question question){
		return Result.OK(questionService.done(question.getId()));
	}


	/**
	 *   添加
	 *
	 * @param questionPage
	 * @return
	 */
	@AutoLog(value = "问题-添加")
	@ApiOperation(value="问题-添加", notes="问题-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody QuestionPage questionPage) {
		Question question = new Question();
		BeanUtils.copyProperties(questionPage, question);
		questionService.saveMain(question, questionPage.getQuestionTypeMappingList(),questionPage.getTagMappingList(),questionPage.getMyQuestionPlanList());
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param questionPage
	 * @return
	 */
	@AutoLog(value = "问题-编辑")
	@ApiOperation(value="问题-编辑", notes="问题-编辑")
	@PostMapping(value = "/edit")
	public Result<?> edit(@RequestBody QuestionPage questionPage) {
		Question question = new Question();
		BeanUtils.copyProperties(questionPage, question);
		Question questionEntity = questionService.getById(question.getId());
		if(questionEntity==null) {
			return Result.error("未找到对应数据");
		}
		PlanEffective planEffective = new PlanEffective();
		BeanUtils.copyProperties(questionPage,planEffective);
		question.setPlanEffective(planEffective);
		questionService.updateMain(question, questionPage.getQuestionTypeMappingList(),questionPage.getTagMappingList(),questionPage.getMyQuestionPlanList());
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "问题-通过id删除")
	@ApiOperation(value="问题-通过id删除", notes="问题-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) Long id) {
		questionService.delMain(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "问题-批量删除")
	@ApiOperation(value="问题-批量删除", notes="问题-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.questionService.delBatchMain(Arrays.asList(ids.split(",")).stream().map(Long::parseLong).collect(Collectors.toList()));
		return Result.OK("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "问题-通过id查询")
	@ApiOperation(value="问题-通过id查询", notes="问题-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) Long id) {
		Question question = questionService.getById(id);
		if(question==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(question);

	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "问题分类方案关联表通过主表ID查询")
	@ApiOperation(value="问题分类方案关联表主表ID查询", notes="问题分类方案关联表-通主表ID查询")
	@GetMapping(value = "/queryQuestionTypeMappingByMainId")
	public Result<List<QuestionTypeMapping>> queryQuestionTypeMappingListByMainId(@RequestParam(name="id",required=true) Long id) {
		List<QuestionTypeMapping> questionTypeMappingList = questionTypeMappingService.selectByMainId(id);
		return Result.OK(questionTypeMappingList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "标签关联表通过主表ID查询")
	@ApiOperation(value="标签关联表主表ID查询", notes="标签关联表-通主表ID查询")
	@GetMapping(value = "/queryTagMappingByMainId")
	public Result<?> queryTagMappingListByMainId(@RequestParam(name="id",required=true) Long id) {
		List<TagMapping> tagMappingList = tagMappingService.selectByMainId(id,1);
		return Result.OK(tagMappingList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "我的问题解决方案通过主表ID查询")
	@ApiOperation(value="我的问题解决方案主表ID查询", notes="我的问题解决方案-通主表ID查询")
	@GetMapping(value = "/queryMyQuestionPlanByMainId")
	public Result<?> queryMyQuestionPlanListByMainId(@RequestParam(name="id",required=true) Long id) {
		List<MyQuestionPlan> myQuestionPlanList = myQuestionPlanService.selectByMainId(id);
		return Result.OK(myQuestionPlanList);
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param question
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, Question question) {
		// Step.1 组装查询条件查询数据
		QueryWrapper<Question> queryWrapper = QueryGenerator.initQueryWrapper(question, request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		//Step.2 获取导出数据
		List<Question> queryList = questionService.list(queryWrapper);
		// 过滤选中数据
		String selections = request.getParameter("selections");
		List<Question> questionList = new ArrayList<Question>();
		if(oConvertUtils.isEmpty(selections)) {
			questionList = queryList;
		}else {
			List<String> selectionList = Arrays.asList(selections.split(","));
			questionList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		}

		// Step.3 组装pageList
		List<QuestionPage> pageList = new ArrayList<QuestionPage>();
		for (Question main : questionList) {
			QuestionPage vo = new QuestionPage();
			BeanUtils.copyProperties(main, vo);
			List<QuestionTypeMapping> questionTypeMappingList = questionTypeMappingService.selectByMainId(main.getId());
			vo.setQuestionTypeMappingList(questionTypeMappingList);
			List<TagMapping> tagMappingList = tagMappingService.selectByMainId(main.getId(),1);
			vo.setTagMappingList(tagMappingList);
			List<MyQuestionPlan> myQuestionPlanList = myQuestionPlanService.selectByMainId(main.getId());
			vo.setMyQuestionPlanList(myQuestionPlanList);
			pageList.add(vo);
		}

		// Step.4 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "问题列表");
		mv.addObject(NormalExcelConstants.CLASS, QuestionPage.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("问题数据", "导出人:"+sysUser.getRealname(), "问题"));
		mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
		return mv;
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<QuestionPage> list = ExcelImportUtil.importExcel(file.getInputStream(), QuestionPage.class, params);
				for (QuestionPage page : list) {
					Question po = new Question();
					BeanUtils.copyProperties(page, po);
					questionService.saveMain(po, page.getQuestionTypeMappingList(),page.getTagMappingList(),page.getMyQuestionPlanList());
				}
				return Result.OK("文件导入成功！数据行数:" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(),e);
				return Result.error("文件导入失败:"+e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.OK("文件导入失败！");
	}

}
